import { AfterViewInit, Component, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { DragDrop } from '@angular/cdk/drag-drop';
import { RoleService } from '../../service/role.service';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import { dataPermissionType } from '../../../../../common/dicData';

@Component({
    selector: 'app-data-permission-option',
    templateUrl: './index.html',
    styleUrls: ['./index.scss'],
})
export class DataPermissionOptionComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('modalContent') modalContent: any;
    @ViewChild('modalFooter') modalFooter: any;
    modalLoadingState: boolean;
    saveLoadingState: boolean;
    entity: any = {} as any;
    modalRef: NzModalRef; //操作弹窗
    deptList: any[] = []; //全部菜单
    checkedKeys: any[] = []; //已经选择的菜单
    dataPermissionType: any[] = dataPermissionType;
    constructor(
        public _config: ConfigModule,
        private _nzModalService: NzModalService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private mainService: RoleService,
    ) {
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
    }

    /**
     * 打开操作弹窗
     */
    onModalOpen(id: string) {
        this.entity.roleId = id;
        this.modalRef = this._nzModalService.create({
            nzTitle: "分配数据权限",
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: this._config.modalWidth,
            nzBodyStyle: {
                ...this._config.modalContentHeight
            },
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            for (const key of Object.keys(this.entity)) {
                delete this.entity[key];
            }
        });

        if (id) {
            this.getDeptTree(id);
            this.modalLoadingState = true;
            this.mainService.get(id).subscribe((res) => {
                if (res.success) {
                    this.entity = res.data;
                    this.modalLoadingState = false;
                }
            });
        }
    }

    getDeptTree(roleId: string){
        this.mainService.getDeptTree(roleId).subscribe((res) => {
            if (res.success) {
                this.deptList = this.convertTreeToList(res.depts);
                this.checkedKeys = res.checkedKeys;
            }
        });
    }

    convertTreeToList(data:any[]): Array<NzTreeNodeOptions> {
        if (!data) return;
        let treeData: NzTreeNodeOptions[] = [];
        data.forEach(node => {
            let treeNode: NzTreeNodeOptions={} as NzTreeNodeOptions;
            treeNode.title = node.label;
            treeNode.expanded = false;
            treeNode.key = node.id;
            treeNode.children = this.convertTreeToList(node.children);
            if (!treeNode.children){
                treeNode.isLeaf = true;
            }
            treeData.push(treeNode);
        })
        return treeData
    }

    /**
     * 保存
     */
    onSave() {
        this.saveLoadingState = true;
        this.entity.deptIds = this.checkedKeys;
        if (this.entity.dataScope!=='2'){
            this.entity.deptIds = [];
        }
        this.mainService.dataScope(this.entity).subscribe((res) => {
            if (res.success) {
                this.modalRef.close();
                for (const key of Object.keys(this.entity)) {
                    delete this.entity[key];
                }
            }
        }).add(() => this.saveLoadingState = false);
    }
}
